package com.hch.datastructure.stack;

public class ArrayStack<T> {
    private int maxSize; // 栈的大小
    private T[] stack; // 数组，数组模拟栈，数据就放在该数组
    private int top = -1;// top表示栈顶，初始化为-1

    //构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = (T[]) new Object[this.maxSize];
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(T value) {
        if (isFull()) {
            throw new RuntimeException("栈空间已满");
        }
        top++;
        stack[top] = value;
    }

    public T pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈已空");
        }
        T value = stack[top];
        top--;
        return value;
    }

    //显示栈的情况[遍历栈]， 遍历时，需要从栈顶开始显示数据
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空，没有数据~~");
            return;
        }
        //需要从栈顶开始显示数据
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }

    public T peek() {
        return stack[top];
    }

}